package com.cssw.fyzb.core.mao.user;

import com.cssw.fyzb.core.model.mos.UserFollowMo;
import com.cssw.fyzb.core.mongo.MongoClient;
import com.cssw.fyzb.core.util.DocUtil;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * @author Feng Chen
 */
@Component
public class UserFollowMaoImpl implements UserFollowMao {

    @Autowired
    private MongoClient mongoClient;

    @Override
    public UserFollowMo findByUserId(Long userId) {
        Document doc = mongoClient.getCollection("user_follow")
                .find(new Document("userId", userId))
                .first();
        return DocUtil.decoce(doc, UserFollowMo.class);
    }

    @Override
    public void save(UserFollowMo userFolllowMo) {
        mongoClient.getCollection("user_follow")
                .insertOne(DocUtil.encode(userFolllowMo));
    }

    @Override
    public void addFollow(Long userId, Long followId) {

        createIfNull(userId);

        mongoClient.getCollection("user_follow").updateOne(
                new Document("userId", userId),
                new Document("$addToSet", new Document("follows", followId))
        );
    }

    @Override
    public void removeFollow(Long userId, Long followId) {
        mongoClient.getCollection("user_follow").updateOne(
                new Document("userId", userId),
                new Document("$pull", new Document("follows", followId))
        );
    }

    @Override
    public boolean exists(Long userId, Long followId) {
        UserFollowMo userFollowMo = findByUserId(userId);

        if (null == userFollowMo || null == userFollowMo.getFollows()){
            return false;
        }

        return userFollowMo.getFollows().contains(followId);
    }

    private void createIfNull(Long userId) {
        UserFollowMo folllowMo = findByUserId(userId);
        if (folllowMo == null) {
            folllowMo = new UserFollowMo();
            folllowMo.setUserId(userId);
            folllowMo.setFollows(Collections.emptyList());
            save(folllowMo);
        }
    }


}
